<template>
  <div class="sale-list">
    <el-container class="container-box">
      <!-- 搜索查询 -->
      <el-header
        height="auto"
        class="header-search">
        <RecordInfo
          :record-form="TOP_CONFIRM"
          :record-data="recordData" />
      </el-header>
      <!-- 列表模块 -->
      <el-editable
        v-loading="tableLoading"
        :data="wholesaleOrderList"
        height="400px"
        :custom-attr="$TABLE_HEAD['beforeSettle.distributorSide.salesManagement.wholesaleOrder']"
        :columns="CONFIRM_COLUMNS"
      >
        <template
          slot="default-registrationNumber"
          slot-scope="scope">
          <div>
            <cell-registration
              :key="scope.row.registrationNumber"
              :regis-no="scope.row.registrationNumber"
              :content="'注册证已过期，点击查看详细信息'"
              :status="scope.row.isNoExpire"
              :regis-data="scope.row.registrationInfo"
            />
          </div>
          <!-- <el-button
            :disabled="!scope.row.registrationNumber||!scope.row.registrationId"
            v-html="regisNoButton(scope.row)"
            @click="showPdfRegistion(scope.row.registrationId)"
            type="text"
          /> -->
        </template>
        <template
          slot="default-supplierId"
          slot-scope="scope">
          <el-select
            v-model="scope.row.supplierId"
            placeholder="请选择">
            <el-option
              v-for="(item,index) in providerList"
              :key="index"
              :label="item.companyName"
              :value="item.companyId"/>
          </el-select>
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
    </el-container>
    <audit-dialog
      :dialog-visible.sync="auditDialogShow"
      :is-reject="isRejectAudit"
      @submitAudit="handleSubmitAudit"
      @closeDialog="auditDialogShow = false"
    />
  </div>
</template>

<script>
import ElEditable from '@components/el-editable/index.vue'
import RecordInfo from '@/moduleComponents/common/detail/recordInfo'
import CellRegistration from '@/moduleComponents/common/detail/cell-registration'
import { isObject, cloneDeep, hasIn } from 'lodash'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common.js'
import {
  TOP_CONFIRM,
  CONFIRM_COLUMNS,
  supplierOptions,
  ORDER_STATUS_TEXT
} from './const'
import {
  deliveryOcBsNeedeedSale,
  deliveryOcBsNeedneed,
  deliveryOcBsNeedSaleSixdelivery,
  deliverySixDeliveryRefuseSaleItem,
  deliveryOcBsSixneedSale,
  deliveryOneedSaleConfirm
} from '@const/beforeSettleApi'
import AuditDialog from '@/moduleComponents/beforeSettle/distributorSide/salesManagement/auditDialog'
import { partnerList } from '@const/authCenterApi'
import { getFormatterPrice } from '@const/filter'
import { regisNoButton, showPdfRegistion } from '@const/agencySaas'
export default {
  name: 'SaleList',
  components: { ElEditable, RecordInfo, AuditDialog, CellRegistration },

  data () {
    return {
      CONFIRM_COLUMNS,
      submitLoading: false,
      TOP_CONFIRM,
      // table列表配置信息
      tableLoading: false,
      // 分页配置信息
      curPage: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0],
      totalElements: 0,
      supplierValue: '',
      supplierOptions,
      isRejectAudit: false,
      auditDialogShow: false,
      recordData: {},
      wholesaleOrderList: [],
      providerList: [],
      isDisabled: true,
      ORDER_STATUS_TEXT,
      orderId: ''
    }
  },

  mounted () {
    // this.getBatchConfirmOrderList()
    this.initButton()
    this.getdeliverySixPurchaseById()
    this.getdeliverySixPurchaseItem()
    this.getProviderList()
  },
  methods: {
    regisNoButton,
    showPdfRegistion,
    back () {
      this.$router.go(-1)
    },
    initButton () {
      let obj = {}
      obj = {
        type: 'btn',
        arr: [
          {
            type: 'button',
            noReturn: true,
            val: '返回',
            handle: this.back
          },
          {
            type: 'danger',
            val: '拒绝订单',
            handle: this.handleAuditReject,
            disabled: this.isDisabled
          },
          {
            type: 'primary',
            val: '确认订单',
            handle: this.handleAuditPass,
            disabled: this.isDisabled
          }
        ]
      }
      this.$store.commit('changeLayoutHandle', obj)
    },
    getProviderList () {
      this.providerLoading = true
      const params = {
        partnership: 'provider',
        registered: 2 // 是否注册，0-未注册，1-已注册，2-全部
      }
      this.$axios
        .$get(partnerList, { params })
        .then(res => {
          this.providerList = res.payload
          console.log(res.payload)
        })
        .catch(e => {})
        .finally(() => {
          this.providerLoading = false
        })
    },
    getdeliverySixPurchaseItem () {
      this.$axios({
        method: 'post',
        data: {
          id: this.$route.query.id
        },
        url: deliveryOcBsNeedneed
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        this.wholesaleOrderList = obj.content || []
        this.totalElements = obj.totalElements
        if (this.wholesaleOrderList.length !== 0) {
          this.isDisabled = false
        }
        this.initButton(true)
      })
    },
    getdeliverySixPurchaseById () {
      this.$axios({
        method: 'post',
        params: {
          id: this.$route.query.id
        },
        url: deliveryOcBsNeedeedSale
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        this.recordData = obj
        this.orderId = obj.id
        for (let key in this.recordData) {
          if (!this.recordData[key] && this.recordData[key] !== 0) {
            this.recordData[key] = `--`
            continue
          }
          if (key === 'orderStatus') {
            this.recordData[key] = this.ORDER_STATUS_TEXT[this.recordData[key]]
          }
          if (key === 'orderTotalAmount') {
            this.recordData[key] = getFormatterPrice(this.recordData[key])
          }
        }
      })
    },
    handleSizeChange (size) {
      this.curPage = 1
      this.pageSize = size
      this.getWholesaleOrderList()
    },
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getWholesaleOrderList()
    },
    // 拒绝订单
    handleAuditReject () {
      this.isRejectAudit = true
      this.auditDialogShow = true
    },
    // 确认订单
    handleAuditPass () {
      this.isRejectAudit = false
      this.auditDialogShow = true
    },
    reTurnListMap () {
      // return this.wholesaleOrderList.map(item => {
      //   return {
      //     id: item.id,
      //     orderId: item.orderId,
      //     supplierId: item.supplierId,
      //     supplierName: this.providerList.filter(ite => {
      //       return ite.companyId === item.supplierId
      //     })[0]
      //       ? this.providerList.filter(ite => {
      //           return ite.companyId === item.supplierId
      //         })[0].companyName
      //       : ''
      //   }
      // })
      // return this.wholesaleOrderList.map(item => {
      //   return {
      //     orderId: item.orderId,
      //     ocBsSaleOrderSixItemFormList: {
      //       supplierId: item.supplierId,
      //       supplierName: this.providerList.filter(ite => {
      //         return ite.companyId === item.supplierId
      //       })[0]
      //         ? this.providerList.filter(ite => {
      //             return ite.companyId === item.supplierId
      //           })[0].companyName
      //         : ''
      //     },
      //     orderItemId:item.orderItemId
      //   }
      // })
      return [
        {
          needOrderId: this.orderId,
          ocBsNeedSaleSixItemFormList: this.wholesaleOrderList.map(item => {
            return {
              orderItemId: item.id,
              supplierId: item.supplierId,
              supplierName: this.providerList.filter(ite => {
                return ite.companyId === item.supplierId
              })[0]
                ? this.providerList.filter(ite => {
                  return ite.companyId === item.supplierId
                })[0].companyName
                : ''
            }
          })
        }
      ]
    },
    handleSubmitAudit () {
      if (!this.isRejectAudit) {
        this.$axios({
          method: 'post',
          url: deliveryOneedSaleConfirm,
          data: this.reTurnListMap()
          // data: this.wholesaleOrderList.length ? this.reTurnListMap() : []
        })
          .then(res => {
            if (res.data.code === '0') {
              this.$message({ type: 'success', message: '提交成功' })
              this.$router.go(-1)
            } else {
              this.$message({ type: 'warning', message: '提交失败' })
              this.auditDialogShow = false
            }
          })
          .catch(res => {
            this.$message({ type: 'warning', message: '提交失败' })
            this.auditDialogShow = false
          })
      } else if (this.isRejectAudit) {
        this.$axios({
          method: 'post',
          url: deliveryOcBsSixneedSale,
          data: {
            needOrderId: this.$route.query.id
          }
        })
          .then(res => {
            if (res.data.code === '0') {
              this.$message({ type: 'success', message: '提交成功' })
              this.$router.go(-1)
            } else {
              this.$message({ type: 'warning', message: '提交失败' })
              this.auditDialogShow = false
            }
          })
          .catch(res => {
            this.$message({ type: 'warning', message: '提交失败' })
            this.auditDialogShow = false
          })
      }
    }
  }
}
</script>

<style lang="less">
.sale-list {
  .header-search {
    .custom-search-form .filter-box .el-form-item__label {
      margin-right: 10px;
      white-space: nowrap;
    }
  }

  .container-box {
    height: 100%;
    overflow: auto;

    .btn-box {
      margin: 12px;
    }

    .pagination {
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      padding-right: 0;
    }
  }
}
</style>
